import { getAppVersion } from '@/api/configure.js';
import configUrl from '@/util/url.js';

let getLocalAppVersion = async() => {
	return await new Promise((resolve, reject) => {
		plus.runtime.getProperty(plus.runtime.appid, (wgtinfo) => {
			resolve(wgtinfo.version);
		});
	}) 
}


export class AutoUpdate {
	constructor() {
		this.app_version = '';
		this.app_Local_version = '';
		this.update_content = '';
		this.platform = '';
		this.subDownloadUrl ='';
		this.timer = null;
		
		this.getPlatform();
	}
	async getAppNewVersion() {
		await getAppVersion().then((res) => {
			this.app_version = res.data.app_version;
			this.update_content = res.data.update_content;
			this.subDownloadUrl = res.data.url;
		})
	}
	
	async getLocalAppVersion() {
		let version = await getLocalAppVersion();
		
		this.app_Local_version = version;
	}
	
	async updeteApp() {
		let _this = this;
		
		return await new Promise((resolve, reject) => {
			uni.showModal({
				title: "版本更新",
				content: this.update_content, //更新描述
				confirmText: '立即更新',
				cancelText: '稍后进行',
				success: sucRes => {
					resolve(sucRes);
				}
			})
		}) 
	}
	
	getPlatform() {
		uni.getSystemInfo({
			success: (e) => {
				this.platform = e.platform;
			}
		})
	}
	
	async doUpData() {
		return await new Promise((resolve, reject) => {
			if(this.platform == 'android'){
				uni.showLoading({
					title: '更新中……'
				})
				uni.downloadFile({ //执行下载
					url: `${configUrl.Setting}${this.subDownloadUrl}` , //下载地址
					success: data => { //下载成功
						uni.hideLoading();
						if (data.statusCode == 200) {
							uni.showModal({
								title: '',
								content: '更新成功，确定现在安装吗？',
								confirmText: '安装',
								confirmColor: '#EE8F57',
								success: function(res) {
									if (data.statusCode === 200) {
										plus.runtime.install(data.tempFilePath, {
											force: true
										}, function(res) {
											resolve(res)
											utils.showToast('更新成功，重启中');
											plus.runtime.restart();
										});
									}
								}
							});
						}
					}
				});
			}
		})
	}
	
	async pause() {
		if(this.timer) {
			clearTimeout(this.timer);
			this.timer = null;
		}
	}
	
	async cycle() {
		if(this.timer) {
			clearTimeout(this.timer);
		}
		
		await this.getAppNewVersion();
		await this.getLocalAppVersion();
		
		if( this.app_Local_version != this.app_version ) {
			let {confirm} = await this.updeteApp();
			
			if(confirm) {
				await this.doUpData();
			}
		} 
		
		this.timer = setTimeout(this.cycle.bind(this), 15000);
	}
}